package jeconbond.economic.systems.market;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.List;

import jeconbond.economic.resources.IResourceType;

public class DefaultMarketResourceRedestributionSystem implements IMarketResourceRedestributionSystem {
	private Map<IResourceType, List<ISellProposition>> resource2props = 
		new HashMap<IResourceType, List<ISellProposition>>();
	private List<ISellsListener> listeners = new ArrayList<ISellsListener>();
	private ISelectPropsStrategy selectPropsStrategy;
	
	public DefaultMarketResourceRedestributionSystem(
			ISelectPropsStrategy selectPropsStrategy
	) {
		this.selectPropsStrategy = selectPropsStrategy;
	}
	
	public DefaultMarketResourceRedestributionSystem() {
		this(SelectPropsStrat.SELECT_ALL_INSTANCE);
	}

	@Override
	public ISellProposition[] getSellPropositionsList(IResourceType rt) {
		List<ISellProposition> props = get(rt);
		ISellProposition[] result = selectPropsStrategy.select(props); 
		return result;
	}

	@Override
	public void registerProposition(ISellProposition sellProposition) {
		get(sellProposition.getType()).add(sellProposition);
	}

	@Override
	public void addSellsListener(ISellsListener listener) {
		listeners.add(listener);
	}

	@Override
	public void onSellPerformed(ISellProposition proposition, double value, IMoneyAccount buyerMoney) {
		for (ISellsListener listener : listeners) {
			listener.onSellPerformed(proposition, value, buyerMoney);
		}
	}

	@Override
	public void onProduceStageCompleted() {
		resource2props.clear();
	}

	@Override
	public Collection<ISellProposition> getSellPropositionsCollection() {
		List<ISellProposition> result = new ArrayList<ISellProposition>();
		for (List<ISellProposition> props : resource2props.values()) {
			result.addAll(props);
		}
		return result;
	}

	private List<ISellProposition> get(IResourceType rt) {
		List<ISellProposition> list = resource2props.get(rt);
		if (list == null) {
			resource2props.put(rt, new ArrayList<ISellProposition>());
		}
		return resource2props.get(rt);
	}
}
